package com.example.springboot.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.mapper.UserMapper;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.ServerException;

/**
 * 功能
 * 作者：八滴水
 * 日期： 2024/12/22 16:59
 */
public class JwtInterceptor implements HandlerInterceptor {
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){

        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }
        if(handler instanceof HandlerMethod){
            AuthAccess authAccess = ((HandlerMethod)handler).getMethodAnnotation(AuthAccess.class);
            if(authAccess != null){
                return true;
            }
        }
        if(StrUtil.isBlank(token)){
            throw new ServiceException("401","请登录1");
        }
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        } catch(JWTDecodeException j){
            throw new ServiceException("401","请登录2");
        }
        User user =  userMapper.selectById(Integer.valueOf(userId));
        if(user == null){
            throw new ServiceException("401","请登录3");
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try{
            jwtVerifier.verify(token);//验证token
        }catch (JWTDecodeException e){
            throw new ServiceException("401","请登录4");
        }
        return true;
    }
}
